package com.haifeng.jupiter.common.redis.aop;

import com.haifeng.jupiter.common.redis.annotation.Lock;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 分布式锁Aop
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-08-15
 */
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class LockAop implements Ordered {

    private final RedissonClient redissonClient;

    @Pointcut("@annotation(com.haifeng.jupiter.common.redis.annotation.Lock)")
    public void lockMethod() {
    }

    @Around("lockMethod()")
    public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        Object[] args = pjp.getArgs();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        Lock annotation = targetMethod.getAnnotation(Lock.class);
        // 获取key
        String lockKey = annotation.key();
        // 获取等待时间
        Integer waitTime = annotation.waitTime();
        // 获取释放时间
        Integer leaseTime = annotation.leaseTime();
        RLock lock = redissonClient.getLock(lockKey);
        try {
            // 尝试加锁，默认等待15秒，15秒后自动释放锁
            boolean tryLock = lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
            if (tryLock) {
                return pjp.proceed();
            }
        } catch (Exception e) {
            log.error("redissonClient exception：{}", e.getMessage());
            throw new Exception("服务器异常，请稍后再试");
        } finally {
            try {
                if (lock != null && lock.isLocked()){
                    lock.unlock();
                }
            } catch (Exception e) {
            }
        }
        throw new Exception("服务器异常，请稍后再试");
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
